// pages/category/category.js
import {request} from "../../request/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftList:[],
    rightList:[],
    currentIndex:0,
    scrollTop:0
  },
  cateDate:[],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const cateDate = wx.getStorageSync('cateDate');
    if(!cateDate){
      //本地没数据
      this.getCategoryList()
    }else{
      //本地有数据
      if(Date.now()-cateDate.time>1000*10){//数据已过期
        this.getCategoryList()
      }else{
        //数据没有过期
        this.cateDate = cateDate.data;
        let leftList = this.cateDate.map(item=>item.cat_name)
        let rightList = this.cateDate[0].children
        console.log(leftList);
        console.log(rightList);
        this.setData({
          leftList,
          rightList
        })
      }
    }
  },

  async getCategoryList(){
    const res = await request({
      url:"/categories"
    })
    console.log(res);
    this.cateDate = res;
    //请求数据存本地
    wx.setStorageSync('cateDate', {
      time:Date.now(),
      data:this.cateDate
    })
    let leftList = this.cateDate.map(item=>item.cat_name)
    let rightList = this.cateDate[0].children
    this.setData({
      leftList,
      rightList
    })
  },
  handleTap(e){
    const {index} = e.currentTarget.dataset;
    let rightList = this.cateDate[index].children
    this.setData({
      currentIndex:index,
      rightList,
      scrollTop:0
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})